<template>
  <div class="home">
    <group>
      <cell-box class="goods-item" v-for="item in goods" :key="item.id">
        <div class="left">
          <img :src="item.img" class="pic" alt="图片">
        </div>
        <div class="right">
          <span class="title">{{item.title}}</span>
          <span class="desc">{{item.desc}}</span>
          <span class="price">¥<i>{{item.price}}</i>元</span>
          <button @click="buy(item)" class="btn-buy">购买</button>
        </div>
        <div class="clear"></div>
      </cell-box>
    </group>
  </div>
</template>
<script>
import { Group, CellBox } from 'vux';
import {addToShopCart,getShopCart} from '../utils/shop_cart'
import {getGoodsData} from '../service/goods'
import Cookies from 'js-cookie'

export default {
  name: 'Home',
  components: {
    Group,
    CellBox,
  },
  data() {
    return {
      goods: [],
    };
  },
  methods: {
    buy(item) {
      if(Cookies.get('user')){
        addToShopCart(item.id,1); // 加入购物车
      // this.$vux.toast.show({
      //   text: `id:${item.id},title:${item.title}`,
      // });
      // $emit派发事件
      //  参数一 事件类型
      //  参数二 事件传递的参数
        this.$eventBus.$emit('ToShopCart', item);
      }

    },
  },
  created(){
    getShopCart()
    this.goods = getGoodsData();
  }
};
</script>
<style scoped>
.clear{
  clear: both;
}
.goods-item{
  display: block;
}
.goods-item .left{
  float: left;
}
.goods-item .right{
  width: 120px;
  float: right;
  margin-left: 4rem;
}
.goods-item .pic{
  display: block;
  width:100px;
  max-height: 200px;
  margin: 20px auto;
}
.goods-item span{
  display: block;
}
.goods-item .title{
  color: #333;
  font-size: 1.2rem;
}
.goods-item .desc{
  color: #9a9a9a;
  font-size: 0.8rem;
}
.goods-item .price{
  color: #666;
  font-size: 1rem;
}
.goods-item .price i{
  color: #ff3300;
}
.goods-item .btn-buy{
  border:1px solid gray;
  border-radius: 4px;
  display: block;
  margin: 0.8rem 0;
  background-color: #09BB07;
  color: #fff;
  padding: 0.5rem 2rem;
}
.home{
  margin-bottom:50px;
}
</style>


